package br.org.etec.dotcao.mailer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mailer {

	private String subject;
	private String fileContent;
	
	private String charset = "utf-8";
	
	private Receiver replyTo;
	private Sender sender;
	private Set<Receiver> receivers = new HashSet<Receiver>();

	public void setSender(Sender sender) {
		this.sender = sender;
	}

	public void addReceiver(Receiver receiver) {
		if (receiver == null) {
			return;
		}
		
		receivers.add(receiver);
	}
	
	public void setSubject(String subject) {
		this.subject = subject;
	}
	
	public void setFileContent(String fileContent) {
		this.fileContent = fileContent;
	}
	
	public void setCharset(String charset) {
		this.charset = charset;
	}
	
	public void setReplyTo(Receiver replyTo) {
		this.replyTo = replyTo;
	}
	
	public void send(){
		try {
			Session session = session();
			
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(sender.getEmail(), sender.getName(), charset));
			
			if(receivers.size() == 0){
				return;
			}
			
			Address[] addresses = new Address[receivers.size()];
			int position = 0;

			for(Receiver receiver : receivers){
				addresses[position++] = new InternetAddress(receiver.getEmail(), receiver.getName());
			}

			message.addRecipients(Message.RecipientType.TO, addresses);
			message.setSubject(subject, charset);
			
			if(replyTo != null){
				message.setReplyTo(new Address[] { new InternetAddress(replyTo.getEmail(), replyTo.getName()) });
			}
			
			message.setText(content());
			
			Transport.send(message);
		} catch (Exception e) {
			throw new RuntimeException("Ocorreu um erro durante o envio do e-mail", e);
		}
		
	}
	
	private String content(){
		return new ContentReader(fileContent).read().get();
	}
	
	private Session session(){
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.user", sender.getEmail());
		
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(sender.getEmail(), sender.getPassword());
			}
		};
		
		Session session = Session.getDefaultInstance(props, authenticator);
		session.setDebug(true);
		
		try {
			File mailOut = new File("mail-out.log");
			
			if(!mailOut.exists()){
				mailOut.createNewFile();
			}
			
			BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(mailOut));
			PrintStream out = new PrintStream(stream);
			
			session.setDebugOut(out);
			
		} catch (Exception e) {
			try {
				LogBuilder.errorLogger(getClass()).error("Erro ao criar o arquivo de log para o envio de e-mails", e);
			} catch (IOException e1) {
				e.printStackTrace();
			}
		}
		
		
		return session;
	}

}
